<?php
/**
 *  Require source specification as
 *  { table-alias: table-name }
 *  where table-name is a string, too
 *
 *  Intending to use this class as the parent of all SelectTree*
 *
 */
namespace Dclub\modules\Catalog;

class Action_SelectTreeAbstract
    extends \Yz\modules\Generic\Action_Select
{

    const TABLE_INDEX = 'i0';
    const TABLE_INDEX_DEPTH = 'd0';
    const TABLE_TREE  = 't0';

    /** the name of tree table
     *  @var string
     */
    protected $tableTree;

    /** the name of index table
     *  @var string
     */
    protected $tableIndex;

    /** the name of depth table
     *  @var string
     */
    protected $tableDepth;


    /************************************
     *      Common Public methods       *
     ************************************/


    /**
     *  @return Yz_Hash
     */
    public function fetch()
    {
        return $this->getStatement()->fetchAll();
    }


    /************************************
     *       Protected methods          *
     ************************************/


    /**
     *  overridable/extensible SELECT statement creator
     *  @return SQL_SELECT
     */
    protected function buildSelect()
    {
        debug();
        $sql = parent::buildSelect();

        // pass through join-builder
        return $this->buildJoin($sql);
    }



    /** assign source tables and enforce correct join for the tables
     *  @param Yz_Hash $tableList
     *  @return chainable
     *  @throw Yz_Exception if table list empty
     *  @throw Yz_Exception if incorrect index table specification
     */
    protected function assignTables(\Yz_Hash $tableList)
    {
        $tree = $tableList[self::TABLE_TREE];
        if (! is_string($tree)) {
            throw new \Yz_Exception("Unrecognized tree table specification: string expected");
        }
        $this->tableTree = $tree;
        $index = $tableList[self::TABLE_INDEX];
        if (! is_string($index)) {
            throw new \Yz_Exception("Unrecognized index table specification: string expected");
        }
        $this->tableIndex = $index;
        $this->tableDepth = $index;

        // required settings for buildSelect
        $this->primaryTable = self::TABLE_TREE;
        $this->tableList = new \Yz_Hash(array(self::TABLE_TREE => $tree));
        return $this;
    }

    /** overridable/extensible join-builder
     *  by default, it joins only the index table
     *
     *  @param SQL_SELECT
     *  @return SQL_SELECT
     */
    protected function buildJoin($sql)
    {
        return $sql
            ->joinTable(
                \Yz_SQL_Join::leftJoin($this->tableIndex, self::TABLE_INDEX)
                    ->joinUsing('id')
            )
        ;
    }


}
